﻿using Jesai.DynamicDataSource.Sqlsugar.ConnManagers;
using Jesai.DynamicDataSource.Sqlsugar.DbConn;
using JESAI.Core.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Jesai.DynamicDataSource.Sqlsugar.DynamicDatasources
{
    public class DbProvider : IDbProvider
    {
        public SqlSugarScope DB { get; private set; }

        public async Task InitDataSourceAsync(List<DBConnection> connections)
        {
            List<ConnectionConfig> connConfigs = new List<ConnectionConfig>();
            foreach (var item in connections)
            {
                var conn = new ConnectionConfig()
                {
                    ConfigId = item.Name,
                    ConnectionString = item.ConnectionString,
                    DbType = item.DbType,
                    IsAutoCloseConnection = item.IsAutoCloseConnection
                };
                //DB.AddConnection(conn);
                connConfigs.Add(conn);
                DBConnectionManager.Add(item.Name, item);
            }
            DB = new SqlSugarScope(connConfigs);
        }

        public async Task<SqlSugarProvider> GetConnection(string connectionName)
        {
            return DB.GetConnection(connectionName);
        }

        public async Task<SqlSugarScopeProvider> GetConnectionThreadSafe(string connectionName)
        {
            return DB.GetConnectionScope(connectionName);
        }

        public async Task AddConnection(DBConnection connection)
        {
            //先判断是否存在连接
            var conn = DB.GetConnection(connection.Name);
            if (conn == null)
            {
                var connConfig = new ConnectionConfig()
                {
                    ConfigId = connection.Name,
                    ConnectionString = connection.ConnectionString,
                    DbType = connection.DbType,
                    IsAutoCloseConnection = connection.IsAutoCloseConnection
                };
                DB.AddConnection(connConfig);
            }
        }

        public async Task RemoveConnection(string connectionName)
        {
            var conn = DB.GetConnection(connectionName);
            //conn.Close();
            DB.RemoveConnection(connectionName);
            DBConnectionManager.Remove(connectionName);
        }

    }
}
